import sys

from flask import Flask, Blueprint, request, render_template, flash, jsonify, url_for
from flaskr.db import get_db
from flaskr import user



bp = Blueprint('model', __name__, url_prefix='/model')

def get_model_main_nos():
    db = get_db()
    mains = db.execute("SELECT DISTINCT main FROM models").fetchall()

    main_nos = []
    for main in mains:
        main_nos.append(main[0])

    return main_nos

def get_model_sub_nos(main_specify=None):
    db = get_db()
    if main_specify is None:
        subs = db.execute("SELECT DISTINCT sub FROM models").fetchall()
    else:
        subs = db.execute("SELECT DISTINCT sub FROM models WHERE main=?", (main_specify,)).fetchall()

    sub_nos = []
    for sub in subs:
        sub_nos.append(sub[0])

    return sub_nos

def get_model_sub_nos_and_descs(main_specify=None):
    db = get_db()
    if main_specify is None:
        subs = db.execute("SELECT DISTINCT sub,desc FROM models").fetchall()
    else:
        subs = db.execute("SELECT DISTINCT sub,desc FROM models WHERE main=?", (main_specify,)).fetchall()

    sub_nos_and_descs = {}
    for sub_no_and_desc in subs:
        sub_nos_and_descs[sub_no_and_desc['sub']] = sub_no_and_desc['desc']

    return sub_nos_and_descs


def model_all_nos():
    all_nos = {}
    main_nos = get_model_main_nos()
    for main_no in main_nos:
        sub_nos = get_model_sub_nos(main_no)
        all_nos[main_no] = sub_nos
    return all_nos


def model_is_exist(main_specify, sub_specify):
    db = get_db()
    r = db.execute("SELECT * FROM models WHERE main=? AND sub=?", (main_specify, sub_specify)).fetchone()
    return r is not None


@bp.route('/', methods=('get', 'post'))
@bp.route('/entry', methods=('get', 'post'))
@user.login_required_as_super_ret("")
def entry():
    main_new = ''
    sub_new = ''
    desc_new = ' '

    db = get_db()
    if request.method == 'POST':
        main_new = request.form.get('Main')
        sub_new = request.form.get('Sub')
        desc_new = request.form.get('Desc')
        action = request.form.get('action')
        if action == 'Create':
            if main_new is None or main_new == '':
                flash("Main No. is needed!")
            elif model_is_exist(main_new, sub_new):
                flash("Model is exist.")
            else:
                db.execute("INSERT INTO models (main, sub, desc) VALUES (?, ?, ?)", (main_new, sub_new, desc_new))
                db.commit()
        elif action == 'Delete':
            if main_new is None or main_new == '':
                flash("Main No. is needed!")
            elif sub_new is None:
                flash("Sub No. is needed!")
            else:
                db.execute("DELETE FROM models WHERE main=? AND sub=?", (main_new, sub_new))
                db.commit()

    models = {}
    mains = get_model_main_nos()
    for main in mains:
        models[main] = get_model_sub_nos_and_descs(main)

    print(models, file=sys.stderr)

    return render_template('model/entry.html', models=models, main_new=main_new, sub_new=sub_new, desc_new=desc_new)


@bp.route('/fetch', methods=('get',))
@bp.route('/fetch/<mainModel>', methods=('get',))
@user.login_required_ret("failed")
def fetchModels(mainModel=None):
    models = {}
    mains = []
    if mainModel is not None and mainModel != "":
        mains.append(mainModel)
    else:
        mains = get_model_main_nos()
    for main in mains:
        models[main] = get_model_sub_nos(main)
    return jsonify(models)
